package com.ruoyi.boat.tcp.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * datacenter
 *
 * 3/24/2022 - 8:39 AM
 */
@Slf4j
@Getter
@Setter
public class NettyClient {

    private String host;
    private Integer port;
    private BdType bdType;
    private TcpClientStarter starter;

    public NettyClient(String host, Integer port,BdType bdType,TcpClientStarter starter) {
        this.host = host;
        this.port = port;
        this.bdType = bdType;
        this.starter = starter;
        //start();
    }

    private SocketChannel socketChannel;

    public void sendMsg(byte[] message) {
        socketChannel.writeAndFlush(Unpooled.copiedBuffer(message));
    }

    public boolean connectFailed = true;

    public void start() {
        log.info("Tcp server connecting");
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .remoteAddress(host, port)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline()
//                                .addLast(new IdleStateHandler(0, 0, 60))
                                .addLast(new DelimiterBasedFrameDecoder(2048, new ByteBuf[]{Unpooled.wrappedBuffer(new byte[]{'\r', '\n'})}))
                                .addLast(new TcpClientHandler(NettyClient.this));
                    }
                });
        ChannelFuture future = bootstrap.connect();
        //客户端断线重连逻辑
        future.addListener((ChannelFutureListener) future1 -> {
            if (future1.isSuccess()) {
                log.info("Tcp server {}:{} connected", host, port);
                connectFailed = false;
            } else {
                log.info("Tcp server {}:{} connection failed, waiting for reconnection", host, port);
                connectFailed = true;
                future1.channel().eventLoop().schedule(this::start, 10, TimeUnit.SECONDS);
            }
        });
        socketChannel = (SocketChannel) future.channel();
    }

    public void close(){
        if(socketChannel != null){
            socketChannel.close();
        }
    }
}